import face_recognition
import cv2
import numpy as np
from com.py.test.face_recogn.FaceRecognWeb import ft2

class FaceRecognPhoto:
    # 抓取一帧视频
    def recognFace(self,frame):
        # 加载示例图片并学习如何识别它。
        zhoujielun_image = face_recognition.load_image_file("D:/picture/zhoujielun.jpg")
        zhoujielun_face_encoding = face_recognition.face_encodings(zhoujielun_image)[0]

        # 创建已知人脸编码及其名称的数组
        known_face_encodings = [
            zhoujielun_face_encoding,
        ]
        known_face_names = [
            "周杰伦",
        ]

        # Initialize some variables
        face_locations = []
        face_encodings = []
        face_names = []
        process_this_frame = True
        data = {}

        # 将视频帧的大小调整为1/4，以便更快地进行人脸识别处理
        small_frame = cv2.resize(frame, (0, 0), fx=1, fy=1)

        # 将图像从bgr颜色（opencv使用）转换为rgb颜色（人脸识别使用）
        rgb_small_frame = small_frame[:, :, ::-1]

        # 只处理其他每帧视频以节省时间
        if process_this_frame:
            # 查找当前视频帧中的所有面和面编码
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

            face_names = []
            for face_encoding in face_encodings:
                # 查看人脸是否与已知人脸匹配
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"

                # # 如果在已知的面部编码中发现匹配，只需使用第一个。
                # if True in matches:
                #     first_match_index = matches.index(True)
                #     name = known_face_names[first_match_index]

                # 或者，使用与新面距离最小的已知面
                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = np.argmin(face_distances)
                if matches[best_match_index]:
                    name = known_face_names[best_match_index]
                face_names.append(name)

        process_this_frame = not process_this_frame
        # Display the results
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            # 自我们检测到的帧被缩放到1/4大小后，将备份面位置缩放
            #远距离检测
            top *= 1
            right *= 1
            bottom *= 1
            left *= 1

            # 在脸上画一个方框
            # cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
            # 在面下绘制一个名称为的标签
            # font = cv2.FONT_HERSHEY_DUPLEX
            # cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (0,0, 0),1)

            data.__setitem__("left",left)
            data.__setitem__("top",top)
            data.__setitem__("right",right)
            data.__setitem__("bottom",bottom)
            data.__setitem__("name",name)

        # Display the resulting image
        # cv2.imshow('text', frame)
        # cv2.waitKey()
        # cv2.destroyAllWindows()
        return data
